package com.znsd.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerUtil {
	public void download(HttpServletRequest request,HttpServletResponse response,Map<String,Object> exportMap) {
		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");                                       //注意这里要设置编码
 
		configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");
		Template t = null;
		try {
			t = configuration.getTemplate("template1.ftl","utf-8");    // 文件名 还有这里要设置编码
		} catch (Exception e) {
			e.printStackTrace();
		}
		File outFile = null;
		Writer out = null;
		String filename = "";
		try {
			filename =""+exportMap.get("studentId")+"试题分析";
			outFile = File.createTempFile(filename, ".doc");
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(outFile),"utf-8"));                 //还有这里要设置编码
			
		} catch (Exception e1) {
			e1.printStackTrace();
		}
 
		try {
			t.process(exportMap, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		InputStream fis = null;
		OutputStream toClient = null;
		try {
			fis = new BufferedInputStream(new FileInputStream(outFile));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			filename = URLEncoder.encode(filename, "utf-8"); //这里要用URLEncoder转下才能正确显示中文名称
			response.addHeader("Content-Disposition", "attachment;filename=" + filename+".doc");
			response.addHeader("Content-Length", "" + outFile.length());
			toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(fis!=null){
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(toClient!=null){
					toClient.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
